package tool

import (
	"database/sql/driver"
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
)

type MyTime time.Time

//
func (t *MyTime) UnmarshalJSON(data []byte) error {
	fmt.Println(12312313234)
	if string(data) == "null" {
		return nil
	}
	var err error
	//前端接收的时间字符串
	str := string(data)
	//去除接收的str收尾多余的"
	timeStr := strings.Trim(str, "\"")
	t1, err := time.Parse("2006-01-02 15:04:05", timeStr)
	*t = MyTime(t1)
	return err
}

func (t MyTime) MarshalJSON() ([]byte, error) {
	var formatted string
	chTime := time.Time(t)
	if chTime.Unix() == 0 {
		formatted = fmt.Sprintf("\"%v\"", 0)
	} else {
		formatted = fmt.Sprintf("\"%v\"", time.Time(t).Format("2006-01-02 15:04:05"))
	}
	return []byte(formatted), nil
}

func (t MyTime) Value() (driver.Value, error) {

	// MyTime 转换成 time.Time 类型
	tTime := time.Time(t)
	return tTime.Format("2006-01-02 15:04:05"), nil
}

// Scan valueof time.Time 一进来就加载
func (ts *MyTime) Scan(v interface{}) error {
	if timeA, ok := v.([]uint8); ok {
		var timeStr string
		for _, u := range timeA {
			timeStr += string(rune(u))
		}
		timeNtime, err := strconv.Atoi(timeStr)
		if err != nil {
			return errors.New("数据类型错误")
		}
		resTime := int64(timeNtime / 1000)
		okTime := time.Unix(resTime, 0)
		*ts = MyTime(okTime)
	}
	if timeA, ok := v.(int64); ok {
		timeNtime := int(timeA)
		resTime := int64(timeNtime / 1000)
		okTime := time.Unix(resTime, 0)
		*ts = MyTime(okTime)
	}
	return nil
}
